package training.bms.presentation;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringEscapeUtils;

@FacesConverter("PostContentConverter")
public class PostContentConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		String stringValue = (String) value;
		StringBuilder newValue = new StringBuilder();
		
		stringValue = StringEscapeUtils.escapeHtml(stringValue);
		
		for(int index = 0; index < stringValue.length(); index++){
			char c1 = stringValue.charAt(index);
			
			if(c1 == '\r' || c1 == '\n'){
				newValue.append("<br/>");
				int nextIndex = index + 1;
				if(nextIndex < stringValue.length()){
					char c2 = stringValue.charAt(nextIndex);
					if( (c1 == '\r' && c2 == '\n') || (c1 =='\n' && c1 == '\r') ){
						index++;
					}
				}
			}else{
				newValue.append(c1);
			}
		}
		
		return newValue.toString();
	}
	
}
